<template>
  <div class="upload-container">
    <el-upload
      :action="uploadUrl"
      :file-list="fileList"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      list-type="picture-card"
      :multiple="true"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    
    <el-dialog v-model="dialogVisible" title="预览">
      <img :src="dialogImageUrl" style="width: 100%" alt="">
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import http from '@/utils/http'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  imageUrl: {
    type: Function,
    default: (url) => url
  }
})

const emit = defineEmits(['update:modelValue', 'on-success'])

const uploadUrl = ref(http.adornUrl('/sys/oss/upload'))
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 监听图片变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    fileList.value = newVal.split(',').map(url => ({
      url: props.imageUrl(url),
      name: url.split('/').pop()
    }))
  } else {
    fileList.value = []
  }
}, { immediate: true })

// 上传成功
const handleUploadSuccess = (response, file, fileList) => {
  if (response && response.code === '00000') {
    const urls = fileList.map(file => {
      return file.response ? file.response.data : file.url
    })
    emit('update:modelValue', urls.join(','))
    emit('on-success', response, file)
}
}

// 预览图片
const handlePreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 移除图片
const handleRemove = (file, fileList) => {
  const urls = fileList.map(file => {
    return file.response ? file.response.data : file.url.split('/').pop()
  })
  emit('update:modelValue', urls.join(','))
}

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}
</script>

<style scoped>
.upload-container {
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  
  .el-upload-list--picture-card .el-upload-list__item {
    width: 100px;
    height: 100px;
  }
}
</style>
